﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Web;
using System.Web.Http;
using ChinapnrAPI;
using DTCash.DistributedLock;
using DTCash.Logger;
using DTCash.Logger.NodeLog.Model;
using DTCash.Redis;
using Microsoft.Ajax.Utilities;
using Uranus.Common;
using Uranus.Service.OrderService;
using Uranus.Service.OtherService;
using Uranus.Service.ProductService;
using Uranus.Service.RepaymentService;
using Uranus.Service.UserService;
using Uranus.WeiStationAPI.App_Start;
using Uranus.WeiStationAPI.Common;
using Uranus.WeiStationAPI.Models;


namespace Uranus.WeiStationAPI.Controllers
{
    public class UserController : BaseController
    {
        //
        // GET: /User/

        #region 获取用户信息

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost, HttpGet]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.ObtainUserInfo)]
        public ResultResPonse GetUserInfo()
        {
            string type = GetParmsKey<string>("type");
            //获取用户体验金 2017年10月12日19:08:35 GUO 去掉体验金
            //OrderItemResponse orderItemResponse = Service.Order.GetOrder().GetUserExperiencerOrderItem(new UserOrderItemRequest()
            //{
            //    UserID = UserInfo.UserID
            //});
            //decimal experienceEarning = 0;//已收到的体验金总额
            //decimal experiencePredicEarning = 0;//预期的体验金总额
            //List<decimal> incomingList = new List<decimal>();
            //if (orderItemResponse != null && orderItemResponse.Code == 1 && orderItemResponse.OrderItemDtos != null && orderItemResponse.OrderItemDtos.Count > 0)
            //{
            //    foreach (OrderItemDTO orderItemDto in orderItemResponse.OrderItemDtos)
            //    {
            //        if (orderItemDto.OrderItemStatusID == 4 && orderItemDto.UserGiftCardStatusID == 2)
            //        {
            //            experienceEarning = experienceEarning + orderItemDto.Price;
            //        }
            //        else if (orderItemDto.OrderItemStatusID == 2)
            //        {
            //            experiencePredicEarning = experiencePredicEarning + orderItemDto.Price;
            //        }
            //    }
            //}
            if (type == "nohide")
            {

            }
            else
            {
                UserInfo.IDCard = Uranus.Common.Validates.SetHideIDCard(UserInfo.IDCard);
                UserInfo.FullName = Uranus.Common.Validates.SetHideFullName(UserInfo.FullName);
            }
            //加字段返回的话，登录注册也要改
            resultResPonse.code = 1;
            resultResPonse.data = new
            {
                IDCard = UserInfo.IDCard,
                //Email = UserInfo.Email,
                //EmailAuthStatusID = UserInfo.EmailAuthStatusID,
                CashFreezePrice = UserInfo.CashFreezePrice,
                InvestFreezePrice = UserInfo.InvestFreezePrice,
                DQAllInvestedPrice = UserInfo.DQAllInvestedPrice,
                DQPredictEarning = UserInfo.DQPredictEarning,
                DQInvestingPrice = UserInfo.DQInvestingPrice,
                UsablePrice = UserInfo.UsablePrice,
                DQEarning = UserInfo.DQEarning,
                Mobile = UserInfo.Mobile,
                //MobileAuthStatusID = UserInfo.MobileAuthStatusID,
                FullName = UserInfo.FullName,
                InvitationCode = UserInfo.InvitationCode,
                IDCardAuthStatusID = UserInfo.IDCardAuthStatusID,
                CreateTime = UserInfo.CreateTime,
                HuiFuCode = UserInfo.HuiFuCode,
                Day = DateTime.Now.Date.Subtract(UserInfo.CreateTime.Date).TotalDays + 1,
                HuiFuName = UserInfo.HuiFuName,
                HuiFuCreateTime = UserInfo.HuiFuCreateTime,
                ExtraProfit = UserInfo.ExtraProfit,
                UserPhoto = UserInfo.UserPhoto,
                CurrentInvestingPrice = UserInfo.CurrentInvestingPrice,
                CurrentShortProfit = UserInfo.CurrentShortProfit,
                CurrentYesterdayProfit = UserInfo.CurrentYesterdayProfit,
                CurrentTotalProfit = UserInfo.CurrentTotalProfit
                //BankCard = UserInfo
                //ExperiencePredicEarning = experiencePredicEarning,
                //ExperienceEarning = experienceEarning
            };
            return Send(resultResPonse);
        }
        #endregion

        #region 获取用户投资列表
        /// <summary>
        /// 获取定期投资列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse DqInvestmentList()
        {
            int index = GetParmsKey<int>("index");
            int size = GetParmsKey<int>("size");
            index = index < 1 ? 1 : index;
            size = size < 1 ? 10 : size;
            string type = GetParmsKey<string>("type");
            if (string.IsNullOrEmpty(type))
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            List<int> productStatusIDs = null;
            if (type == "1")//持有中
            {
                productStatusIDs = new List<int>() { 3, 4, 5 };
            }
            else if (type == "2")//已到期
            {
                productStatusIDs = new List<int>() { 6, 7 };
            }
            UserInvestmentResponse userInvestmentRes = Uranus.Service.Order.GetOrder().GetInvestmentDTOList(new Service.OrderService.UserInvestmentRequest()
            {
                UserID = UserInfo.UserID,
                PageIndex = index,
                PageSize = size,
                ProductGroupIDs = new List<int>() { 1, 2 },
                ProductStatusIDs = productStatusIDs
            });
            List<UserInvestmentDTO> userInvestmentDtos = new List<UserInvestmentDTO>();
            int total = 0;
            if (userInvestmentRes != null)
            {
                userInvestmentDtos = userInvestmentRes.UserInvestmentDtos ?? new List<UserInvestmentDTO>();
                total = userInvestmentRes.TotalNum;
                foreach (UserInvestmentDTO item in userInvestmentDtos)
                {
                    if (item.ProductStatusID == 3)
                    {
                        LoanProductDTO dto = (Service.Product.GetProduct().GetLoanProductByCode(new LoanProductRequest()
                        {
                            LoanProductDto = new LoanProductDTO()
                            {
                                ProductCode = item.ProductCode
                            }
                        }) ?? new LoanProductResponse()).LoanProductDto;
                        if (dto != null)
                        {
                            //同步数据
                            ControllerCommon.SyncLoanProductProgress(dto);
                            item.ProductStatusID = dto.ProductStatusID;
                        }
                    }
                    //计算收益
                    if (item.ProductStatusID < 5)
                    {
                        RepaymentScheduleDTO repaymentScheduleDto = Uranus.Service.Repayment.GetRepayment().RepaymentSchedule(item.OrderItemPrice, item.AnnualRateOfYear, item.LoanPeriod, item.RepaymentTypeID);
                        if (repaymentScheduleDto != null)
                        {
                            item.RepayInterest = repaymentScheduleDto.InvestInterest;//投资利息
                            //InvestPrice 投资金额  InvestPrincipal本息
                        }
                    }
                }
            }
            resultResPonse.code = 1;
            resultResPonse.data = new
            {
                total = total,
                list = userInvestmentDtos.Select(a => new
                {
                    AnnualRateOfYear = a.AnnualRateOfYear,
                    a.GiftCardRate,
                    ProductCode = a.ProductCode,
                    ProductStatusID = a.ProductStatusID,
                    ProductName = a.ProductName,
                    PaymentTime = Uranus.Common.DateCommon.ConvertDateTimeString(a.PaymentTime),
                    OrderItemPrice = a.OrderItemPrice,
                    OrderItemID = a.OrderItemID,
                    MaxRepayDate = Uranus.Common.DateCommon.ConvertDateTimeString(a.MaxRepayDate),
                    FullConfirmTime = Uranus.Common.DateCommon.ConvertDateTimeString(a.FullConfirmTime),
                    RepayInterest = a.RepayInterest, //预期收益
                    RepayInterested = a.RepayInterested, //已收收益
                    GiftCardInterest = a.GiftCardInterest,
                    GiftCardInterested = a.GiftCardInterested
                })
            };
            return Send(resultResPonse);
        }

        /// <summary>
        /// 获取定期投资记录详情（查询出产品信息和还款记录）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse DqInvestmentInfo()
        {
            int oid = GetParmsKey<int>("oid");
            if (oid > 0)
            {
                try
                {
                    //获取投资产品详情
                    UserInvestmentResponse userInvestRes = Uranus.Service.Order.GetOrder().GetInvestmentDTOList(new UserInvestmentRequest() { UserID = UserInfo.UserID, OrderItemID = oid });
                    if (userInvestRes != null && userInvestRes != null && userInvestRes.UserInvestmentDtos.Count > 0)
                    {
                        UserInvestmentDTO userInvestDto = userInvestRes.UserInvestmentDtos[0];
                        //获取产品还款列表
                        RepaymentItemFormResponse repaymentRes = Uranus.Service.Repayment.GetRepayment().GetRepaymentItemFormDTOList(new Service.RepaymentService.RepaymentItemFormRequest() { OrderItemID = oid });
                        List<Uranus.Service.RepaymentService.RepaymentItemFormDTO> repaymentItemFormDtos = new List<RepaymentItemFormDTO>();
                        if (repaymentRes != null)
                        {
                            repaymentItemFormDtos = repaymentRes.RepaymentItemFormDtos ?? new List<RepaymentItemFormDTO>();
                        }
                        resultResPonse.code = 1;
                        resultResPonse.data = new
                        {
                            ProductName = userInvestDto.ProductName,
                            ProductCode = userInvestDto.ProductCode,
                            ProductStatusID = userInvestDto.ProductStatusID,
                            AnnualRateOfYear = userInvestDto.AnnualRateOfYear,
                            RepaymentTypeName = userInvestDto.RepaymentTypeName,
                            MinRepayDate = Uranus.Common.DateCommon.ConvertDateTimeString(userInvestDto.PaymentTime),
                            MaxRepayDate = Uranus.Common.DateCommon.ConvertDateTimeString(userInvestDto.MaxRepayDate),
                            OrderItemPrice = userInvestDto.OrderItemPrice,
                            RepayInterest = userInvestDto.RepayInterest, //预期收益
                            YiShouInterest = repaymentItemFormDtos.Where(a => a.RepaymentItemFormStatusID == 2).Sum(a => a.RepayInterest + a.RepayPrincipal),
                            repaymentItemFormDtos = repaymentItemFormDtos.Select(a => new
                            {
                                RepaymentItemFormStatusID = a.RepaymentItemFormStatusID,
                                RepayPrincipal = a.RepayPrincipal, //本金
                                RepayTime = Uranus.Common.DateCommon.ConvertDateTimeString(a.RepayTime),//还款时间
                                RepayFee = a.RepayFee, //手续费
                                RepayInterest = a.RepayInterest, //利息
                                Price = a.RepayPrice //本息
                            })
                        };
                    }
                    else
                    {
                        resultResPonse.code = 2;
                    }
                }
                catch (Exception ex)
                {
                    DTCash.Logger.LogHelper.WriteLogError("获取定期投资详情异常", string.Format("子订单编号{0},错误原因:{1}", oid, ex.Message));
                }
            }
            else
            {
                resultResPonse.code = 3;
            }
            return Send(resultResPonse);
        }

        #endregion

        #region 获取用户交易列表
        /// <summary>
        /// 获取用户全部交易记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse UserTransactionList()
        {
            int index = GetParmsKey<int>("index");
            int size = GetParmsKey<int>("size");
            if (index <= 0 || size <= 0)
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            UserTransactionResponse userTransactionRes = Uranus.Service.User.GetUser().GetUserTransactionAllList(new Service.UserService.UserTransactionRequest()
            {
                UserID = UserInfo.UserID,
                PageIndex = index,
                PageSize = size
            }) ?? new UserTransactionResponse();
            List<UserTransactionDTO> userTransactionDtos = userTransactionRes.UserTransactionDtos ?? new List<UserTransactionDTO>();
            resultResPonse.code = 1;
            resultResPonse.data = new
            {
                list = userTransactionDtos.Select(a => new
                {
                    FinishTime = DateCommon.ConvertDateTimeString(a.FinishTime),
                    a.Price,
                    a.UserTransferPropertyID,
                    a.UserTransferTypeID,
                    a.UserTransferTypeName,
                    a.ProductGroupID,
                    a.Fee
                }),
                total = userTransactionRes.TotalNum
            };
            return Send(resultResPonse);
        }
        #endregion

        #region 用户体验金

        /// <summary>
        /// 体验金详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse ExperienceInfo()
        {
            GiftCardResponse giftCardResponse = Service.User.GetUser().GetGiftCardType();
            if (giftCardResponse.Code != 1 || giftCardResponse.GiftCardDtos == null || giftCardResponse.GiftCardDtos.Count == 0)
            {
                resultResPonse.code = 007;
                return Send(resultResPonse);
            }
            int usePeriod = giftCardResponse.GiftCardDtos.Find(p => p.GiftCardTypeID == 1).UsePeriod;

            OrderItemResponse orderItemResponse = Service.Order.GetOrder().GetUserExperiencerOrderItem(new UserOrderItemRequest()
            {
                UserID = UserInfo.UserID
            });
            if (orderItemResponse.Code != 1)
            {
                resultResPonse.code = 007;
                return Send(resultResPonse);
            }
            orderItemResponse.OrderItemDtos = (orderItemResponse.OrderItemDtos ?? new List<OrderItemDTO>()).OrderByDescending(a => a.OrderItemID).ToList();

            UserHomePagePriceResponse userHomePagePriceResponse =
                Service.User.GetUser().GetUserHomePagePriceResponse(UserInfo.UserID);
            if (userHomePagePriceResponse.Code != 1)
            {
                resultResPonse.code = 007;
                return Send(resultResPonse);
            }

            List<decimal> incomedList = new List<decimal>();
            List<decimal> incomingList = new List<decimal>();
            List<decimal> investingPrice = new List<decimal>();
            if (orderItemResponse.OrderItemDtos.Count > 0)
            {
                foreach (OrderItemDTO orderItemDto in orderItemResponse.OrderItemDtos)
                {
                    if (orderItemDto.OrderItemStatusID == 4 && orderItemDto.UserGiftCardStatusID == 2)
                    {
                        incomedList.Add(orderItemDto.Price);
                    }
                    else if (orderItemDto.OrderItemStatusID == 2)
                    {
                        incomingList.Add(orderItemDto.Price);
                    }
                    if (orderItemDto.OrderItemStatusID == 2)
                    {
                        investingPrice.Add(orderItemDto.OrderItemPrice);
                    }
                }
            }
            decimal noviceRate = 18m;
            if (userHomePagePriceResponse.InvestCount == 0 && investingPrice.Count > 0)
            {
                LoanProductResponse loanProductResponse = Service.Product.GetProduct().GetLoanProductDTOList(new LoanProductRequest()
                {
                    ProductGroupIds = new List<int>() { 3 },
                    ProductStatusIds = new List<int>() { 3 },
                    PageIndex = 1,
                    PageSize = 5
                });
                if (loanProductResponse.Code == 1 && loanProductResponse.list.Count > 0)
                {
                    noviceRate = loanProductResponse.list[0].AnnualRateOfYear * 100;
                }
            }
            resultResPonse.code = 1;
            resultResPonse.data = new
            {
                incomed = incomedList.Sum(p => p),
                incoming = incomingList.Sum(p => p),
                investingPrice = investingPrice.Sum(p => p),
                isInvest = userHomePagePriceResponse.InvestCount > 0,
                noviceRate = noviceRate.ToString("f1").Replace(".0", ""),
                list = orderItemResponse.OrderItemDtos.Select(p => new
                {
                    orderItemID = p.OrderItemID,
                    productName = p.ProductName,
                    productCode = p.ProductCode,
                    startTime = p.PaymentTime.ToString("yyyy-MM-dd"),
                    endTime = p.PaymentTime.AddDays(usePeriod - 1).ToString("yyyy-MM-dd"),
                    orderItemPrice = p.OrderItemPrice,
                    price = p.Price,
                    rate = p.AnnualRateOfYear,
                    userGiftCardStatusID = p.UserGiftCardStatusID,
                    orderItemStatusID = p.OrderItemStatusID,
                    days = p.PaymentTime.Date.AddDays(6).Subtract(DateTime.Now.Date).Days,
                    isExpire = p.UserGiftCardStatusID == 3 || p.PaymentTime.Date.AddDays(31) <= DateTime.Now && p.UserGiftCardStatusID == 1
                })
            };
            return Send(resultResPonse);
        }

        #endregion

        #region 获取用户银行卡


        /// <summary>
        /// 获取用户可用银行卡数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse GetUserBankList()
        {
            UserBankCardResponse userBankCardResponse = Service.User.GetUser().GetUserBankCardDTOList(UserInfo.UserID);
            if (userBankCardResponse.Code != 1)
            {
                resultResPonse.code = 006;
                return Send(resultResPonse);
            }
            List<UserBankCardDTO> userBankCardDtos = userBankCardResponse.UserBankCardDtos.Where(p => p.UserBankCardTypeID == 2).ToList();
            resultResPonse.code = 1;
            resultResPonse.data = userBankCardDtos.Select(p => new
            {
                p.UserBankCardID,
                p.BankID,
                p.BankName,
                p.CardNo,
                p.BankNumber
            }).FirstOrDefault();
            return Send(resultResPonse);
        }
        #endregion

        #region 获取用户充值银行

        /// <summary>
        /// 获取用户快捷充值银行
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse GetUserRechargeBank()
        {
            List<ChargeBankInfoDTO> chargeBankInfoDtos =
                chargeBankInfoDtos =
                    Uranus.Common.CodeCommon.DeSerialize<List<ChargeBankInfoDTO>>(ConfigCenterWork.GetConfigValueByOperationType(6).ToString());

            if (chargeBankInfoDtos == null)
            {
                resultResPonse.code = 5;
                resultResPonse.data = "银行信息不存在";
                return Send(resultResPonse);
            }
            resultResPonse.code = 1;
            resultResPonse.data = chargeBankInfoDtos.Select(p => new
            {
                p.BankID,
                p.BankName,
                p.BankNumber,
                p.OnePrice,
                p.TotalPrice
            });

            return Send(resultResPonse);
        }

        #endregion

        #region 开通汇付保存信息
        /// <summary>
        /// 开通汇付保存信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse ConfirmationHuifu()
        {
            string guid = Guid.NewGuid().ToString("N");
            UserShopInfo userShop = new UserShopInfo()
            {
                UserID = UserInfo.UserID
            };
            CacheRedis.AddCache(new TimeSpan(0, 20, 0), CacheItem.InitByIdentity(guid, "Confirmation").Other.other, userShop);
            resultResPonse.code = 1;
            resultResPonse.data = new { gid = guid };
            return Send(resultResPonse);
        }
        #endregion

        #region 提现保存信息
        /// <summary>
        /// 提现保存信息
        /// Date:2017-10-19 00:00:00
        /// Author:Linsan
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.ObtainUserInfo)]
        public ResultResPonse ConfirmationWithdraw()
        {
            string userbankcardid = GetParmsKey<string>("userbankcardid");
            string banknumber = GetParmsKey<string>("banknumber");
            string bankcard = GetParmsKey<string>("bankcard");
            string cashtype = GetParmsKey<string>("cashtype");
            string price = GetParmsKey<string>("price");
            string bankid = GetParmsKey<string>("bankid");

            int userbankcid = 0;
            if (string.IsNullOrEmpty(price) || string.IsNullOrEmpty(banknumber) || string.IsNullOrEmpty(bankcard) || string.IsNullOrEmpty(userbankcardid) || string.IsNullOrEmpty(cashtype) || !int.TryParse(userbankcardid, out userbankcid))
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            if (userbankcid <= 0)
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            if (string.IsNullOrEmpty(UserInfo.HuiFuCode))
            {
                resultResPonse.code = 5;//参数非法
                resultResPonse.data = "未开通汇付";
                return Send(resultResPonse);
            }
            decimal minCashPrice = Convert.ToDecimal(ConfigCenterWork.GetConfigValueByOperationType(1));


            decimal cashPrice = Uranus.Common.Validates.GetDecimal(price);
            if (cashPrice < minCashPrice)
            {
                resultResPonse.code = 0;
                resultResPonse.data = "最少提现金额为" + minCashPrice + "元！";
                return Send(resultResPonse);
            }
            decimal canCashPrice = UserInfo.UsablePrice - UserInfo.CashFreezePrice;
            if (cashPrice > canCashPrice)
            {
                resultResPonse.code = 0;
                resultResPonse.data = "可取现金额不足！";
                return Send(resultResPonse);
            }
            if (!CommonModel.VerificationVersion())
            {
                resultResPonse.code = 0;
                resultResPonse.data = "后台服务验证失败 不予取现 请联系客服！";
                return Send(resultResPonse);
            }
            decimal cashFee = 0m;
            if (cashtype == "quickcash" || cashtype == "currentcash")
            {
                string desc;
                if (!BusinessCommon.VerQuickCashTime(out desc))
                {
                    resultResPonse.code = 0;
                    resultResPonse.data = desc;
                    return resultResPonse;
                }
                object configFastCashBank = ConfigCenterWork.GetConfigValueByOperationType(5);
                if (configFastCashBank != null)
                {
                    string[] supportarray = configFastCashBank.ToString().Split(',');
                    if (!supportarray.Contains(bankid))
                    {
                        resultResPonse.code = 0;
                        resultResPonse.data = "不可快速提现，请更换银行卡！";
                        return Send(resultResPonse);
                    }
                    if (cashtype != "currentcash")
                    {
                        cashFee = CommonModel.FastEnchashmentPoundage(cashPrice);
                        if (cashPrice + cashFee > canCashPrice)
                        {
                            resultResPonse.code = 132;
                            return Send(resultResPonse);
                        }
                    }
                }
                else
                {
                    resultResPonse.code = 0;
                    resultResPonse.data = "不可快速提现，请更换银行卡！";
                    return Send(resultResPonse);
                }
            }
            string guid = Guid.NewGuid().ToString("N");
            UserShopInfo userShop = new UserShopInfo()
            {
                CashPrice = cashPrice,
                Fee = cashFee,
                UserBankCardID = userbankcid,
                BankNumber = banknumber,
                CardNo = bankcard
            };
            CacheRedis.AddCache(new TimeSpan(0, 20, 0), CacheItem.InitByIdentity(guid, "Confirmation").Other.other, userShop);
            resultResPonse.code = 1;
            resultResPonse.data = new { gid = guid };
            return Send(resultResPonse);
        }
        #endregion

        #region 充值确认

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse SetRechargeInfo()
        {
            int bankId = Validates.GetInt(GetParmsKey<string>("bankid"));
            string bankCode = GetParmsKey<string>("bankcode");
            decimal price = Validates.GetDecimal(GetParmsKey<string>("price"));
            if (bankId <= 0 || string.IsNullOrEmpty(bankCode) || price <= 0)
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            DateTime now = DateTime.Now;
            if ((now.Hour == 23 && now.Minute >= 55) || (now.Hour == 0 && now.Minute <= 05))
            {
                resultResPonse.code = 0;
                resultResPonse.data = "23:55~00:05为系统维护时段，请稍后再进行充值操作！";
                return Send(resultResPonse);
            }
            decimal minChargePrice = Convert.ToDecimal(ConfigCenterWork.GetConfigValueByOperationType(10));
            if (price < minChargePrice)
            {
                resultResPonse.code = 0;
                resultResPonse.data = "最低充值金额为" + minChargePrice + "元";
                return Send(resultResPonse);
            }
            if (price > 99999999)
            {
                resultResPonse.code = 0;
                resultResPonse.data = "一次性最大充值金额不得超过千万位";
                return Send(resultResPonse);
            }

            string gid = Guid.NewGuid().ToString("N");
            UserShopInfo userShopInfo = new UserShopInfo();
            userShopInfo.ChargePrice = price;
            userShopInfo.BankNumber = bankCode;
            userShopInfo.BankId = bankId;
            CacheRedis.AddCache(new TimeSpan(0, 20, 0), CacheItem.InitByIdentity(gid, "Confirmation").Other.other, userShopInfo);
            resultResPonse.code = 1;
            resultResPonse.data = gid;

            return Send(resultResPonse);
        }

        #endregion

        #region 获取提现手续费

        /// <summary>
        /// 获取提现手续费
        /// Date:2017-10-19 00:00:00
        /// Author:Linsan
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultResPonse GetEnchashmentPoundage()
        {
            string price = GetParmsKey<string>("price");
            if (string.IsNullOrEmpty(price))
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            decimal enchashPrice = Uranus.Common.Validates.GetDecimal(price);
            if (enchashPrice > 0)
            {
                enchashPrice = CommonModel.FastEnchashmentPoundage(enchashPrice);

                resultResPonse.code = 1;
                resultResPonse.data = enchashPrice;
                return Send(resultResPonse);
            }
            resultResPonse.code = 2;
            return Send(resultResPonse);
        }

        #endregion

        #region 验证是否支持快捷提现
        /// <summary>
        /// 验证银行是否支持快捷提现
        /// Date:2017-10-20 00:00:00
        /// Author:Linsan
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultResPonse ValidateIsQuickCash()
        {
            string bankid = GetParmsKey<string>("bankid");
            if (string.IsNullOrEmpty(bankid))
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            object configFastCashBank = ConfigCenterWork.GetConfigValueByOperationType(5);
            if (configFastCashBank != null)
            {
                string[] supportarray = configFastCashBank.ToString().Split(',');
                if (supportarray.Contains(bankid))
                {
                    resultResPonse.code = 1;
                    resultResPonse.data = true;
                    return Send(resultResPonse);
                }
            }
            resultResPonse.code = 1;
            resultResPonse.data = false;
            return Send(resultResPonse);
        }
        #endregion

        #region 获取最小提现金额

        /// <summary>
        /// 获取最小提现金额
        /// Date:2017-10-20 00:00:00
        /// Author:Linsan
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse GetMinCashPrice()
        {
            resultResPonse.code = 1;
            resultResPonse.data = Convert.ToDecimal(ConfigCenterWork.GetConfigValueByOperationType(1));
            return Send(resultResPonse);
        }
        #endregion

        #region 用户消息

        /// <summary>
        /// 根据条件查询用户消息记录
        /// Date:2017-10-23 00:00:00
        /// Author:Linsan
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse GetUserMessage()
        {
            string type = GetParmsKey<string>("type");
            string start = GetParmsKey<string>("start");
            string end = GetParmsKey<string>("end");
            if (string.IsNullOrEmpty(type) || string.IsNullOrEmpty(start) || string.IsNullOrEmpty(end))
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            int pagestart, pageend, typeid;
            if (!int.TryParse(start, out pagestart) || !int.TryParse(end, out pageend) || !int.TryParse(type, out typeid))
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            if (type == "1")
            {
                NewsAllResponse response = Uranus.Service.User.GetUser().GetNewsAllByCondition(new NewsAllRequest()
                {
                    NewsTypeID = 3,
                    NewsStatusID = 1,
                    PageStart = pagestart,
                    PageEnd = pageend
                });
                if (response != null && response.Code == 1)
                {
                    resultResPonse.code = 1;
                    resultResPonse.data = new
                    {
                        total = response.Total,
                        list = response.List.Select(a => new
                        {
                            UserMessageID = a.NewsID,
                            Title = a.NewsTitle,
                            Content = a.NewsContent,
                            UserMessageTypeID = a.NewsTypeID,
                            CreateTime = Uranus.Common.DateCommon.ConvertDateTimeString(a.CreateTime)
                        })
                    };
                    return Send(resultResPonse);
                }
            }
            else if (type == "2")
            {
                UserMessageAllResponse response = Uranus.Service.User.GetUser().GetUserMessageAllByCondition(new UserMessageAllRequest()
                {
                    UserID = UserInfo.UserID,
                    PageStart = pagestart,
                    PageEnd = pageend
                });
                if (response != null && response.Code == 1)
                {
                    resultResPonse.code = 1;
                    resultResPonse.data = new
                    {
                        total = response.Total,
                        list = response.List.Select(a => new
                        {
                            UserMessageID = a.UserMessageID,
                            Title = a.Title,
                            Content = a.Content,
                            UserMessageTypeID = a.UserMessageTypeID,
                            UserMessageStatusID = a.UserMessageStatusID,
                            CreateTime = Uranus.Common.DateCommon.ConvertDateTimeString(a.CreateTime)
                        })
                    };
                    return Send(resultResPonse);
                }
            }

            resultResPonse.code = 2;
            return Send(resultResPonse);
        }

        /// <summary>
        /// 获取用户是否有未读消息
        /// Date:2017-10-23 00:00:00
        /// Author:Linsan
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse GetUserMessageStatus()
        {
            Uranus.Service.UserService.BaseResponse response = Uranus.Service.User.GetUser().GetUserMessageAllStatusIDByUserID(new UserMessageAllRequest()
            {
                UserID = UserInfo.UserID
            });
            if (response != null && response.Code == 1)
            {
                resultResPonse.code = 1;
                resultResPonse.data = response.ResposeData;
                return Send(resultResPonse);
            }
            resultResPonse.code = 2;
            return Send(resultResPonse);
        }

        /// <summary>
        /// 获取用户是否有未读消息
        /// Date:2017-10-23 00:00:00
        /// Author:Linsan
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultResPonse GetUserMessageByID()
        {
            string id = GetParmsKey<string>("id");
            string type = GetParmsKey<string>("type");
            int mid;
            if (string.IsNullOrEmpty(type) || string.IsNullOrEmpty(id) || !int.TryParse(id, out mid))
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            if (type == "1")
            {
                Uranus.Service.UserService.NewsAllResponse response =
                    Uranus.Service.User.GetUser().GetNewsByUserNewsID(new NewsAllRequest()
                    {
                        NewsID = mid
                    });
                if (response != null && response.Code == 1)
                {
                    resultResPonse.code = 1;
                    resultResPonse.data = null;
                    if (response.NewDto != null)
                    {
                        resultResPonse.data = new
                        {
                            Title = response.NewDto.NewsTitle,
                            Content = response.NewDto.NewsContent,
                            CreateTime = Uranus.Common.DateCommon.ConvertDateTimeString(response.NewDto.CreateTime)
                        };
                    }
                    return Send(resultResPonse);
                }
            }
            else if (type == "2")
            {
                Uranus.Service.UserService.UserMessageAllResponse response =
                    Uranus.Service.User.GetUser().GetUserMessageByUserMessageID(new UserMessageAllRequest()
                    {
                        UserMessageID = mid
                    });
                if (response != null && response.Code == 1)
                {
                    resultResPonse.code = 1;
                    resultResPonse.data = null;
                    if (response.UserMessageDto != null)
                    {
                        resultResPonse.data = new
                        {
                            Title = response.UserMessageDto.Title,
                            Content = response.UserMessageDto.Content,
                            CreateTime = Uranus.Common.DateCommon.ConvertDateTimeString(response.UserMessageDto.CreateTime),
                            UserMessageStatusID = response.UserMessageDto.UserMessageStatusID
                        };
                    }
                    return Send(resultResPonse);
                }
            }
            resultResPonse.code = 2;
            return Send(resultResPonse);
        }

        /// <summary>
        /// 修改用户消息状态
        /// Date:2017-10-20 00:00:00
        /// Author:Linsan
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse AuthUserMessage()
        {
            string type = GetParmsKey<string>("type");
            if (string.IsNullOrEmpty(type))
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            try
            {
                UserResponse response = new UserResponse();
                if (type == "1")
                {
                    string id = GetParmsKey<string>("id");
                    int mid;
                    if (string.IsNullOrEmpty(id) || !int.TryParse(id, out mid))
                    {
                        resultResPonse.code = 3;
                        return Send(resultResPonse);
                    }
                    response =
                        Uranus.Service.User.GetUser().UpdateUserMessageByCondition(new UserMessageEditStatusRequest()
                        {
                            UserMessageID = mid
                        });

                }
                else if (type == "2")
                {
                    response =
                        Uranus.Service.User.GetUser().UpdateUserMessageByCondition(new UserMessageEditStatusRequest()
                        {
                            UserID = UserInfo.UserID
                        });
                }
                if (response != null && response.Code == 1)
                {
                    Uranus.Service.Other.GetOther().RemoveModuleCache("usermessagebyuserid", UserInfo.UserID.ToString());
                    resultResPonse.code = 1;
                    return Send(resultResPonse);
                }
            }
            catch
            {
                resultResPonse.code = 6;
                return Send(resultResPonse);
            }
            resultResPonse.code = 2;
            return Send(resultResPonse);
        }

        #endregion

        #region 用户优惠卡

        /// <summary>
        /// 获取用户优惠卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse GetUserGiftCardList()
        {
            string type = GetParmsKey<string>("type");
            List<int> giftCardStatusIDs = new List<int>();
            decimal giftCardSumprofit = 0;
            List<int> giftCardTypeIDs = new List<int>() { 2, 5 };
            if (type == "Invalid")
            {
                //失效优惠卡页面用
                //已使用,已过期
                giftCardStatusIDs.Add(2);
                giftCardStatusIDs.Add(3);
            }
            else if (type == "effectiveAndsumprofit")
            {
                //优惠卡页面用
                Uranus.Service.UserService.BaseResponse baseResponse = Uranus.Service.User.GetUser()
                    .GetGiftCardSumprofit(new GiftCardRequest
                    {
                        UserID = UserInfo.UserID
                    }) ?? new Service.UserService.BaseResponse();

                if (baseResponse.Code == 1)
                {
                    giftCardSumprofit = Convert.ToDecimal(baseResponse.ResposeData);
                }
                //新建
                giftCardStatusIDs.Add(1);
            }
            else if (type == "confirm")
            {
                giftCardTypeIDs = new List<int>() { 2 };
                string gid = GetParmsKey<string>("gid");
                CacheKey cacheKey = CacheItem.InitByIdentity(gid, "Confirmation").Other.other;
                if (!CacheRedis.ExistsRedis(cacheKey))
                {
                    resultResPonse.code = 110;//订单记录不存在
                    return Send(resultResPonse);
                }
                UserShopInfo userShopInfo = CacheRedis.GetCache(cacheKey) as UserShopInfo;
                if (userShopInfo == null || userShopInfo.UserID != UserInfo.UserID)
                {
                    resultResPonse.code = 110;//订单记录不存在
                    return Send(resultResPonse);
                }
                ProductPropertySubDTOResponse productPropertyRes = Uranus.Service.Product.GetProduct()
                    .GetPropertySubByProductCode(new ProductPropertySubDTORequest()
                    {
                        LoanProductPropertySubDto = new LoanProductPropertySubDTO() { ProductCode = userShopInfo.ProductCode }
                    }) ?? new ProductPropertySubDTOResponse();
                if (productPropertyRes != null && productPropertyRes.List != null)
                {
                    giftCardTypeIDs = productPropertyRes.List.Where(p => p.PropertySubID == 38)
                        .Select(p => Validates.GetInt(p.InputValue)).ToList();
                }
                giftCardTypeIDs.Remove(5);
                giftCardStatusIDs.Add(1);
            }
            else
            {
                //用户中心页面用
                giftCardStatusIDs.Add(1);
            }

            //
            GiftCardResponse userInvalidGiftCardListRes = Uranus.Service.User.GetUser().GetUseForGiftCardDTOListByAPI(
                                                              new Service.UserService.GiftCardRequest()
                                                              {
                                                                  UserID = UserInfo.UserID,
                                                                  GiftCardTypeIDs = giftCardTypeIDs,
                                                                  GiftCardStatusIDs = giftCardStatusIDs
                                                              }) ?? new GiftCardResponse();
            List<GiftCardDTO> userTransactionDtos = new List<GiftCardDTO>() { };
            resultResPonse.code = 1;
            //排序
            if (type == "Invalid")
            {
                /*取已经使用的优惠卡信息*/
                GiftCardResponse usedGiftCardDtoListRes = Uranus.Service.User.GetUser()
                                                              .GetUsedGiftCardDTOListByAPI(
                                                                  new Service.UserService.GiftCardRequest()
                                                                  {
                                                                      UserID = UserInfo.UserID
                                                                  }) ?? new GiftCardResponse();

                if (usedGiftCardDtoListRes.Code == 1 && usedGiftCardDtoListRes.GiftCardDtos.Count > 0)
                {
                    /*把已使用的现金卡加到List*/
                    if (userInvalidGiftCardListRes.GiftCardDtos == null)
                    {
                        userInvalidGiftCardListRes.GiftCardDtos = new List<GiftCardDTO>();
                    }

                    userInvalidGiftCardListRes.GiftCardDtos.AddRange(usedGiftCardDtoListRes.GiftCardDtos);
                }
                userTransactionDtos = userInvalidGiftCardListRes.GiftCardDtos.OrderByDescending(a => a.UsedTime).ThenByDescending(a => a.ExpiredTime).ToList();

            }
            else if (type == "effectiveAndsumprofit")
            {
                if (userInvalidGiftCardListRes.GiftCardDtos != null)
                {
                    userTransactionDtos = userInvalidGiftCardListRes.GiftCardDtos.OrderByDescending(a => a.CreateTime).ToList();
                }
            }
            else if (type == "confirm")
            {
                if (userInvalidGiftCardListRes.GiftCardDtos != null)
                {
                    userTransactionDtos = userInvalidGiftCardListRes.GiftCardDtos.Where(p => p.ExpiredTime > DateTime.Now).OrderByDescending(a => a.CreateTime).ToList();
                }
            }

            if (userTransactionDtos == null)
            {
                userTransactionDtos = new List<GiftCardDTO>();
            }

            resultResPonse.data = new
            {
                list = userTransactionDtos.Select(a => new
                {
                    GiftCardFromName = a.GiftCardFromName,
                    GiftCardID = a.GiftCardID,
                    GiftCardFromID = a.GiftCardFromID,
                    GiftCardStatusID = a.GiftCardStatusID,
                    GiftCardTypeName = a.GiftCardTypeName,
                    GiftCardTypeID = a.GiftCardTypeID,
                    GiftCardValue =
                    a.GiftCardTypeID == 5 ? a.GiftCardValue.ToString("f0") : Convert.ToDecimal(a.GiftCardValue * 100).ToString("f2"),
                    CardRate = a.GiftCardValue,
                    CreateTime = a.CreateTime.ToString("yy-MM-dd"),
                    ExpiredTime = a.ExpiredTime.ToString("yy-MM-dd"),
                }),
                GiftCardSumprofit = giftCardSumprofit,
                total = userInvalidGiftCardListRes.GiftCardDtos.Count
            };
            return Send(resultResPonse);
        }


        /// <summary>
        /// 获取首页用户新手标信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.ObtainUserInfo)]
        public ResultResPonse GetUserIndexNoviceInfo()
        {
            GiftCardResponse UserInvalidGiftCardListRes = Uranus.Service.User.GetUser().GetUseForGiftCardDTOListByAPI(
                                                              new Service.UserService.GiftCardRequest()
                                                              {
                                                                  UserID = UserInfo.UserID,
                                                                  GiftCardStatusIDs = new List<int> { 1, 2, 3 },
                                                                  GiftCardTypeIDs = new List<int> { 5 },/*变现卡*/
                                                                  GiftCardFromIDs = new List<int> { 1, 3 } /*来源注册，实名*/
                                                              }) ?? new GiftCardResponse();
            List<GiftCardDTO> userTransactionDtos = UserInvalidGiftCardListRes.GiftCardDtos ?? new List<GiftCardDTO>();
            int isNoviceCashCardDisplay = 1;//新手专享变现卡未登录

            GiftCardDTO registerGiftCardDto = userTransactionDtos.SingleOrDefault(a => a.GiftCardFromID == 1);//注册
            GiftCardDTO realNameGiftCardDto = userTransactionDtos.SingleOrDefault(a => a.GiftCardFromID == 3);//实名

            if (registerGiftCardDto == null)
            {
                registerGiftCardDto = new GiftCardDTO();
            }

            if (realNameGiftCardDto == null)
            {
                realNameGiftCardDto = new GiftCardDTO();
            }

            bool IsDeposit = false;//是否可存入,默认改为False；2018-5-8 20:32:14 刘卓林

            string registerExpiredTime = string.Empty;
            string registerGiftCardValue = string.Empty;

            if (registerGiftCardDto.GiftCardID > 0)
            {
                registerGiftCardValue = registerGiftCardDto.GiftCardValue.ToString("f0");
                registerExpiredTime = registerGiftCardDto.ExpiredTime.ToString("yy-MM-dd");
            }


            string realNameExpiredTime = string.Empty;
            string realNameGiftCardValue = string.Empty;
            if (realNameGiftCardDto.GiftCardID > 0)
            {
                realNameGiftCardValue = realNameGiftCardDto.GiftCardValue.ToString("f0");
                realNameExpiredTime = realNameGiftCardDto.ExpiredTime.ToString("yy-MM-dd");
            }

            if (registerGiftCardDto.GiftCardID == 0 || realNameGiftCardDto.GiftCardID == 0)
            {
                //注册完成没有卡或者实名认证也没有卡,不显示优惠卡
                isNoviceCashCardDisplay = 4;
            }

            if (registerGiftCardDto.GiftCardID > 0 && realNameGiftCardDto.GiftCardID == 0)
            {
                //注册完有卡，但还未实名
                isNoviceCashCardDisplay = 2; //已下发，未实名认证
            }

            if (realNameGiftCardDto.GiftCardID > 0 && realNameGiftCardDto.GiftCardStatusID != 3 &&
                realNameGiftCardDto.GiftCardValue > 0) //因优先使用注册卡，在此只需判断实名卡是否有余额和是否过期
            {
                isNoviceCashCardDisplay = 3; //已实名认证且变现卡有效（未过期且可变现余额不为0）
            }

            if (realNameGiftCardDto.GiftCardID > 0 && (realNameGiftCardDto.GiftCardStatusID == 3 ||
                                                       realNameGiftCardDto.GiftCardValue == 0))
            {
                isNoviceCashCardDisplay = 4; //已实名认证且变现卡失效（过期或可变现余额为0）,不显示变现卡区
            }


            //判断是否可购买，用户实名后再判断
            string noviceExpiredTime = string.Empty;
            if (!string.IsNullOrEmpty(UserInfo.HuiFuCode))
            {
                noviceExpiredTime = UserInfo.HuiFuCreateTime.AddDays(4).ToString("yy-MM-dd");
                if (UserInfo.HuiFuCreateTime.AddDays(5).Date < DateTime.Now ||
                    UserInfo.InvestCount > 0) //判断为当前日期+5天的00:00:00
                {
                    //在实名认证后5天内有效,或有过一笔投资
                    IsDeposit = false;
                }
                else
                {
                    //在实名认证后5天内有效
                    IsDeposit = true;
                }
            }
            else
            {
                //同线上，未实名认证则显示
                IsDeposit = true;
            }

            /*读取配置中心，若取值和当前用户ID一致,则拥有 开通永久存入权限*/
            object noviceWhiteUser = ConfigCenterWork.GetConfigValueByOperationType(15);//新手标白名单用户
            if (noviceWhiteUser != null)
            {
                string[] supportarray = noviceWhiteUser.ToString().Split(',');
                if (supportarray.Contains(UserInfo.UserID.ToString()))
                {
                    IsDeposit = true;//可以购买
                    noviceExpiredTime = string.Empty;//新手标过期时间--无
                }
            }

            /*最后判断如果当前没有新手标 则不显示新手标图片*/
            LoanProductResponse xinshouRes = Service.Product.GetProduct().GetLoanProductDTOList(new LoanProductRequest()
            {
                ProductStatusIds = new List<int>() { 3, 4 }, //募资中,已满标
                ProductGroupIds = new List<int>() { 2 }, //新手标
                PageIndex = 1,
                PageSize = 5
            }) ?? new LoanProductResponse();
            if (xinshouRes.list == null || xinshouRes.list.Count == 0)
            {
                IsDeposit = false;
            }

            resultResPonse.code = 1;
            resultResPonse.data = new
            {
                IsDeposit = IsDeposit,
                isNoviceCashCardDisplay = isNoviceCashCardDisplay,
                registerGiftCardValue = registerGiftCardValue,
                registerExpiredTime = registerExpiredTime,

                realNameGiftCardValue = realNameGiftCardValue,
                realNameExpiredTime = realNameExpiredTime,
                NoviceExpiredTime = noviceExpiredTime //新手标过期时间
            };
            return Send(resultResPonse);
        }

        #endregion

        #region 我的活期
        /// <summary>
        /// 获取活期投资列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse CurrentInvestmentList()
        {
            int index = GetParmsKey<int>("index");
            int size = GetParmsKey<int>("size");
            index = index < 1 ? 1 : index;
            size = size < 1 ? 10 : size;
            UserInvestmentResponse userInvestmentRes = Uranus.Service.Order.GetOrder().GetCurrentInvestmentDtoList(
                new Service.OrderService.UserInvestmentRequest()
                {
                    UserID = UserInfo.UserID,
                    PageIndex = index,
                    PageSize = size
                });
            if (userInvestmentRes != null && userInvestmentRes.Code == 1)
            {
                resultResPonse.code = 1;
                resultResPonse.data = new
                {
                    total = userInvestmentRes.TotalNum,
                    list = userInvestmentRes.UserInvestmentDtos.Select(a => new
                    {
                        AnnualRateOfYear = a.AnnualRateOfYear,
                        ProductCode = a.ProductCode,
                        ProductName = a.ProductName,
                        PaymentTime = Uranus.Common.DateCommon.ConvertDateTimeString(a.PaymentTime),
                        OrderItemPrice = a.OrderItemPrice,
                        OrderItemID = a.OrderItemID
                    }),
                    maxCurProPrice = Convert.ToDecimal(ConfigCenterWork.GetConfigValueByOperationType(23) ?? 0)
                };
            }
            else
            {
                resultResPonse.code = 002;
            }

            return Send(resultResPonse);
        }

        /// <summary>
        /// 获取活期产品可卖出金额
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.ObtainUserInfo, EnAuthHuifu = true)]
        public ResultResPonse GetSellCurrentInfo()
        {
            decimal canSellPrice = ControllerCommon.GetUserCurrentProductSellPrice(UserInfo);
            if (canSellPrice < 0)
            {
                resultResPonse.code = 2;
                return Send(resultResPonse);
            }
            bool isFastBank = false;
            UserBankCardDTO userBankCardDto = ControllerCommon.GetUserFastUserBankCard(UserInfo.UserID);
            if (userBankCardDto == null)
            {
                resultResPonse.code = 006;
                return Send(resultResPonse);
            }
            isFastBank = userBankCardDto.UserBankCardID > 0;
            decimal minCashPrice = Validates.GetDecimal(ConfigCenterWork.GetConfigValueByOperationType(1));
            resultResPonse.code = 1;
            resultResPonse.data = new
            {
                canSellPrice,
                minCashPrice,
                userBankCard = isFastBank
                    ? new
                    {
                        userBankCardDto.UserBankCardID,
                        userBankCardDto.BankID,
                        userBankCardDto.BankName,
                        userBankCardDto.CardNo,
                        userBankCardDto.BankNumber,
                    }
                    : null
            };
            return Send(resultResPonse);
        }

        /// <summary>
        /// 活期取款
        /// </summary>
        /// <returns></returns>
        [HttpPost, UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin,EnAuthHuifu = true)]
        public ResultResPonse SellOutCurrentProduct()
        {
            decimal sellPrice = Validates.GetDecimal(GetParmsKey<string>("price"));
            int sellType = Validates.GetInt(GetParmsKey<string>("selltype"));
            if (sellPrice <= 0 || sellType == 0)
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }

            resultResPonse.code = 0;
            DateTime now = DateTime.Now;
            string desc;
            if (!BusinessCommon.VerCurrentProductSellTime(out desc))
            {
                resultResPonse.data = desc;
                return resultResPonse;
            }
            if (DistributedLock.VerificationLock("currentproductrepayment"))//验证是否在发放收益 此key为wcf发放活期收益时使用的key
            {
                resultResPonse.code = -1;
                resultResPonse.data = "收益正在发放中，请稍后再试";
                return Send(resultResPonse);
            }
            LockDto lockDto;
            try
            {
                lockDto = DistributedLock.GetLockNoTimeOut($"sellcurrent_{UserInfo.UserID}", new TimeSpan(0, 10, 0));
                if (!lockDto.Success)
                {
                    resultResPonse.data = "上次取款操作未完成，请稍后";
                    return resultResPonse;
                }
            }
            catch (Exception ex)
            {
                DTCash.Logger.LogHelper.WriteLogError("卖出活期添加redislock异常",
                    $"userid：{UserInfo.UserID},price:{sellPrice},sellType:{sellType}", ex, true);
                resultResPonse.data = "卖出失败，请重试";
                return resultResPonse;
            }
            decimal canSellPrice = ControllerCommon.GetUserCurrentProductSellPrice(UserInfo);
            if (sellPrice > canSellPrice)
            {
                DistributedLock.RemoveLock(lockDto);
                resultResPonse.data = $"您今日最多可卖出{canSellPrice.ToString("f2").Replace(".00", "")}元";
                return resultResPonse;
            }

            CurrentProductSellResult sellResult = new CurrentProductSellResult();
            int userBankCardId = 0;
            if (sellType == 2)
            {
                decimal minCashPrice = Validates.GetDecimal(ConfigCenterWork.GetConfigValueByOperationType(1));
                if (sellPrice < minCashPrice)
                {
                    DistributedLock.RemoveLock(lockDto);
                    resultResPonse.data = "最少提现金额为" + minCashPrice + "元！";
                    return resultResPonse;
                }
                UserBankCardDTO userBankCardDto = ControllerCommon.GetUserFastUserBankCard(UserInfo.UserID);
                if (userBankCardDto == null)
                {
                    DistributedLock.RemoveLock(lockDto);
                    resultResPonse.code = 6;
                    return Send(resultResPonse);
                }
                userBankCardId = userBankCardDto.UserBankCardID;
            }
            sellResult.SellPrice = sellPrice;
            sellResult.SellType = sellType == 2 ? CurrentProSellType.SellOutBank : CurrentProSellType.SellOutUsable;
            sellResult.UserBankCardId = userBankCardId;

            int sourceTypeId = Validates.GetInt(GetParmsKey<string>("sourceTypeId"));
            string gid = Guid.NewGuid().ToString("N");
            int userId = UserInfo.UserID;
            Action<object> a = (paras) =>
            {
                CurrentProductRepaymentResponse currentProductRepaymentResponse = Service.Repayment.GetRepayment()
                    .SellOutCurrentProduct(new CurrentProductRepaymentRequest()
                    {
                        SellMoney = sellPrice,
                        UserId = userId
                    });
                sellResult.SuccessPrice = currentProductRepaymentResponse.SuccesePrice;
                sellResult.FailPrice = currentProductRepaymentResponse.FailPrice;
                sellResult.ResultMsg = currentProductRepaymentResponse.ResposeData;
                bool isSuccess = sellResult.SuccessPrice == sellPrice;
                if (sellResult.SellType == CurrentProSellType.SellOutUsable)
                {
                    string resultMsg = !isSuccess && string.IsNullOrEmpty(sellResult.ResultMsg) ? "第三方处理异常" : sellResult.ResultMsg;
                    string title = isSuccess ? "活期取出成功" : "活期取出失败";
                    string messag = string.Empty;
                    if (isSuccess)
                    {
                        messag =
                            $"<p>您已从活期取出到账户余额<span style=\"color: #f26308;\">{sellPrice.ToString("N2")}</span>元。</p>";
                    }
                    else if (sellResult.SuccessPrice == 0)
                    {
                        messag =
                            $"<p>您于{DateTime.Now.ToString("yyyy年MM月dd日HH时mm分")}从活期申请取出<span style=\"color: #f26308;\">{sellPrice.ToString("N2")}</span>元到账户余额，由于{resultMsg}取出失败。</p>";
                    }
                    else
                    {
                        messag =
                            $"<p>您于{DateTime.Now.ToString("yyyy年MM月dd日HH时mm分")}从活期申请取出<span style=\"color: #f26308;\">{sellPrice.ToString("N2")}</span>元到账户余额，" +
                            $"其中成功取出<span style=\"color: #f26308;\">{sellResult.SuccessPrice.ToString("N2")}</span>元，" +
                            $"<span style=\"color: #f26308;\">{sellResult.FailPrice.ToString("N2")}</span>元由于{resultMsg}取出失败。</p>";
                    }
                    Uranus.Service.User.GetUser().SendUserMessage(UserInfo.UserID, title, messag);
                }

                if (sellResult.SellType == CurrentProSellType.SellOutBank && sellPrice == sellResult.SuccessPrice)
                {
                    #region 商户代取现

                    MerCashResponse merCashResponse = ControllerCommon.CurrentProductMerCash(UserInfo, sellResult.SuccessPrice, userBankCardId, (ordId) =>
                    {
                        SourceHandle(SourceOperation.Cash, string.Empty, int.Parse(ordId), Uranus.Common.Validates.GetInt(sourceTypeId));
                    });
                    if (merCashResponse.IsSuccess)
                    {
                        sellResult.RespCode = merCashResponse.RespCode;
                        sellResult.RespDesc = merCashResponse.RespDesc;
                        sellResult.OrdId = merCashResponse.OrdId;
                        sellResult.TransactionResultGuid = merCashResponse.TranscationHid;
                    }
                    else
                    {
                        sellResult.ResultMsg = merCashResponse.ResultMsg;
                    }

                    #endregion
                }

                CacheRedis.AddCache(new TimeSpan(0, 20, 0),
                    CacheItem.InitByIdentity(gid, "CurrentProSellResult").Other.other, sellResult);

                DistributedLock.RemoveLock(lockDto);
            };
            a.BeginInvoke(null, null, null);

            resultResPonse.code = 1;
            resultResPonse.data = gid;
            return Send(resultResPonse);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost, UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin,EnAuthHuifu = true)]
        public ResultResPonse GetCurrentProSellResult()
        {
            string gid = GetParmsKey<string>("gid");
            if (string.IsNullOrEmpty(gid))
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            if (!CacheRedis.ExistsRedis(CacheItem.InitByIdentity(gid, "CurrentProSellResult").Other.other))
            {
                resultResPonse.code = 303;
                return Send(resultResPonse);
            }

            CurrentProductSellResult cpsr =
                (CurrentProductSellResult)CacheRedis.GetCache(CacheItem.InitByIdentity(gid, "CurrentProSellResult").Other.other);
            bool isSuccess = cpsr.SellPrice == cpsr.SuccessPrice;
            if (isSuccess)
            {
                if (cpsr.SellType == CurrentProSellType.SellOutBank)
                {
                    if (string.IsNullOrEmpty(cpsr.TransactionResultGuid))
                    {
                        resultResPonse.code = 0;
                        resultResPonse.data = "非常抱歉，汇付取现处理异常，请联系客服进行查询处理结果！";
                        return Send(resultResPonse);
                    }
                }
            }
            else
            {
                cpsr.ResultMsg = string.IsNullOrEmpty(cpsr.ResultMsg) ? "第三方处理异常" : cpsr.ResultMsg;
            }
            resultResPonse.code = 1;
            resultResPonse.data = new
            {
                gid,
                successPrice = cpsr.SuccessPrice,
                failPrice = cpsr.SellPrice - cpsr.SuccessPrice,
                transcationGuid = cpsr.TransactionResultGuid,
                resultMsg = !isSuccess ? cpsr.ResultMsg : string.Empty,
                hid = cpsr.TransactionResultGuid,
                respCode = cpsr.RespCode,
                respDesc = cpsr.RespDesc,
                ordId = cpsr.OrdId
            };


            return Send(resultResPonse);
        }

        /// <summary>
        /// 获取支持快速提现银行卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultResPonse GetSupportQuickBank()
        {
            object configFastCashBank = ConfigCenterWork.GetConfigValueByOperationType(5);
            if (configFastCashBank != null)
            {
                string[] supportarray = configFastCashBank.ToString().Split(',');
                BankListResponse response = Service.User.GetUser().GetBankInfoList();
                if (response.Code != 1)
                {
                    resultResPonse.code = 3;
                    return Send(resultResPonse);
                }
                resultResPonse.code = 1;
                resultResPonse.data = response.BankInfoDtos.Where(p => supportarray.Contains(p.BankID.ToString()))
                    .Select(p => new
                    {
                        p.BankID,
                        p.BankName,
                        p.BankNumber
                    });
                return resultResPonse;

            }
            resultResPonse.code = 2;
            return Send(resultResPonse);
        }
        #endregion
    }
}
